<?php

class deliveryAction extends CommonAction
{
    public function _initialize()
    {
        parent::_initialize();
        $this->suppierids = M('Supplier_user')->Field('supplier_id')->where(array('user_id' => session(C('USER_AUTH_KEY'))))->buildSql();
        $this->is_suppierids = M('Supplier_user')->Field('supplier_id')->where(array('user_id' => session(C('USER_AUTH_KEY'))))->count();

    }

    public function index()
    {
        $this->shippingList = M('Shipping')->where(array('site_id' => $this->siteid, 'status' => 1))->select();
        if ($this->_get('getExcel', 'int') > 0) {
            $this->getExcel = $this->_get('getExcel', 'int');
            $this->getExcel();

        }
        $pagesize = 10;


        if ($this->_get('pagesize')) {
            $pagesize = $this->_get('pagesize');
        }

        $map = "o.status = 2 and s.thtype =0 and o.site_id = " . $this->siteid;


        if (!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0) {
            $map .= ' and s.supplier_id in(' . $this->suppierids . ')';
            $this->suppier = M('Supplier')->where('site_id=' . $this->siteid . ' and id in(' . $this->suppierids . ')')->select();

        } else {
            $this->suppier = M('Supplier')->where('site_id=' . $this->siteid)->select();
        }

        if (isset($_GET['supplier_id']) && intval($_GET['supplier_id']) > 0) {
            $map .= " and s.supplier_id=" . intval($_GET['supplier_id']);
            $this->assign('supplier_id', intval($_GET['supplier_id']));
        }


        if ($this->_get('shipping_id', 'int') || $this->_get('shipping_id') == '0') {
            $map .= " and o.shipping_id = " . $this->_get('shipping_id', 'int');
            $this->shipping_id = $this->_get('shipping_id');
        }
        if ($this->_get('status', 'int') || $this->_get('status') == '0') {
            $map .= " and s.status = " . $this->_get('status', 'int');
            $this->status = $this->_get('status');
        }

        /*if($this->is_suppierids > 0){
            $map .= " and s.supplier_id in(".$this->suppierids.")";
        }*/


        if ($this->_get('keywords')) {
            $map .= " and o.ordernumber like '%" . $this->_get('keywords') . "%'";
        }


        if ($this->_get('stime') || $this->_get('etime')) {

            $stime = strtotime($this->_get('stime'));
            $etime = strtotime($this->_get('etime')) + 24 * 3600;

            if ($this->_get('stime')) {
                $map .= " and o.create_time >= '" . $stime . "'";
                //$map['o.create_time'] = array('gt',$stime);
            }

            if ($this->_get('etime')) {
                $map .= " and o.create_time <= '" . $etime . "'";
            }

            if ($this->_get('etime') && $this->_get('stime')) {
                $map .= " and o.create_time <= '" . $etime . "'";
                $map .= " and o.create_time >= '" . $stime . "'";
            }

        }

        $saleDB = D('sale');
        $count = $saleDB->alias('s')->join('INNER JOIN __ORDER__ as o on o.id = s.order_id')->where($map)->getField('count(distinct(s.order_id)) as tp');

        //实例化分页类
        import('ORG.Util.Page');
        $p = new Page($count, $pagesize);

        $data = $saleDB->alias('s')->join('RIGHT JOIN __ORDER__ as o on o.id = s.order_id')->where($map)->order('create_time DESC')->group("order_id")->limit($p->firstRow . ',
' . $p->listRows) -> Field('s.*,o.ordernumber,o.shipping_status,o.tel,o.yourname,o.address,o.taxtitle') -> select();


        $memberdb = M('Member');
		
		if (!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0) {
            $map .= ' and s.supplier_id in(' . $this->suppierids . ')';
            $this->suppier = M('Supplier')->where('site_id=' . $this->siteid . ' and id in(' . $this->suppierids . ')')->select();

        } else {
            $this->suppier = M('Supplier')->where('site_id=' . $this->siteid)->select();
        }
		
		
        foreach($data as $k => $v){
			if(!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0){
				$data[$k]['total'] = $saleDB -> where("supplier_id in(".$this->suppierids.") and order_id = '".$v['order_id']."'") -> sum('total');
			}else{
				$data[$k]['total'] = $saleDB -> where(array('order_id' => $v['order_id'])) -> sum('total');
			}
			
			$data[$k]['nickname'] = $memberdb -> where(array('id' => $v['member_id'])) -> getField('nickname');
		}


        $pages = $p->show();
        $this->assign('list', $data);
        $this->assign('pages', $pages);
        $this->display();

    }

    public function read()
    {
        $order_id = $this->_get('id');
        $saleDB = M("Sale");
        $map = "s.order_id = '" . $order_id . "' and s.site_id = " . $this->siteid;
        if (isset($_GET['supplier_id']) && intval($_GET['supplier_id']) > 0) {
            $map .= " and s.supplier_id=" . intval($_GET['supplier_id']);
            $this->assign('supplier_id', intval($_GET['supplier_id']));
        }
        if (!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0) {
            $map .= " and s.supplier_id in(" . $this->suppierids . ")";

        }
        $sale = $saleDB->alias('s')->join("left join __PRODUCT__ as p on p.id=s.product_id")->where($map)->Field('s.create_time,s.supplier_id, p.id, p.title, p.img_url, s.price, s.create_time,s.total,s.num,s.logistics_num,p.id,s.attr')->select();
		//echo $saleDB -> getLastSql();
        $attrvalDB = M('attr_val');
        foreach ($sale as $k => $v) {

            $attrval = explode(';', $v['attr']);
            $sale[$k]['attrmes'] = array();

            foreach ($attrval as $v) {
                $mes = $attrvalDB->where(array('id' => $v))->find();
                array_push($sale[$k]['attrmes'], $mes['val']);
            }
        }
        $this->assign('list', $sale);
        $this->display();
    }

    //金额总计
    public function totalamount(key,url){
        $order_id = $this->_get('id');//获取选中的所有id
        $saleDB = M("Sale");
        $map = "s.order_id = '" . $order_id . "' and s.site_id = " . $this->siteid;
        dump($order_id);
        // $sale = $saleDB->alias('s')->join("left join __PRODUCT__ as p on p.id=s.product_id")->where($map)->Field('s.create_time,s.supplier_id, p.id, p.title, s.price, s.create_time,s.total,s.num,s.logistics_num,p.id,s.attr')->select();

        // $attrvalDB = M('attr_val');

        // foreach ($sale as $k => $v) {
        //     $attrval = explode(';', $v['attr']);
        //     $sale[$k]['attrmes'] = array();
        //     foreach ($attrval as $v) {
        //         $mes = $attrvalDB->where(array('id' => $v))->find();
        //         array_push($sale[$k]['attrmes'], $mes['val']);
        //     }
        // }
        $this->assign('list', $sale);
        $this->display();
    }


    //订单发货
    public function logistics()
    {

        $order_id = $this->_post('order_id');
        $logistics_num = $this->_post('logistics_num');
        //更新物流单号
        $orderDB = D('Order');
        $saleDB = M('sale');
        $memberDB = M('member');
        //判断是否支付
        $order = $orderDB->where(array('id' => $order_id))->find();
        if ($order['status'] != 2) {

            $this->error("订单尚未支付");
            exit;
        }

        $map = "order_id = '" . $order_id . "' and site_id = " . $this->siteid;


        if (!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0) {
            $map .= " and supplier_id in(" . $this->suppierids . ")";

        }


        $endtime = time();

        $mes = $saleDB->where($map)->save(array('logistics_num' => $logistics_num, 'status' => 1, 'endtime' => ($endtime + 86400 * 7)));
        //dump($saleDB -> getLastSql());exit;
        $orderDB->updateshipping($order_id, $this->siteid);
        //更新订单状态

        if ($mes) {
            //推送状态
            $member = $memberDB->where(array('id' => $order['member_id']))->find();
            $stitle = M('shipping')->where(array('id' => $order['shipping_id']))->getField('title');

            $domain = M('Site')->where(array('id' => $this->siteid))->getField('domain');
            if ($domain == '') {
                $siteid = $this->siteid;
            } else {
                $siteid = 0;
            }

            $text = "您的订单" . $order['ordernumber'] . "已经发货，配送方式：" . $stitle . " \n 快递单号:" . $logistics_num . "　<a href=\"" . U('Member/Order/read', array('id' => $order_id), true, false, true, $siteid) . "\">点击查询快递进度</a>";
            sendWXMsg($member['openid'], $text);
            $this->success("发货成功");
        } else {
            $this->error("更新订单失败" . $saleDB->getLastSql() . $saleDB->getError());
        }
    }

    //导出发货明细
    public function getExcel()
    {

        Vendor('Excel.PHPExcel');
        $excel = new PHPExcel();


        set_time_limit(0);
        //取出数据
        $saleDB = D('sale');
        $productDB = M('product');


        $map = "o.status = 2 and s.pay_status in(2,1) and o.site_id = " . $this->siteid;
        if ($this->_get('shipping_id', 'int') || $this->_get('shipping_id') == '0') {


            $map .= " and o.shipping_id = " . $this->_get('shipping_id', 'int');


            $this->shipping_id = $this->_get('shipping_id');
        }
        if ($this->_get('status', 'int') || $this->_get('status') == '0') {


            $map .= " and s.status = " . $this->_get('status', 'int');


            $this->status = $this->_get('status');
        }
        if ($this->_get('stime') || $this->_get('etime')) {

            $stime = strtotime($this->_get('stime'));
            $etime = strtotime($this->_get('etime')) + 24 * 3600;


            if ($this->_get('etime') && $this->_get('stime')) {
                $map .= " and o.create_time <= " . $etime;
                $map .= " and o.create_time >= " . $stime;


            } elseif ($this->_get('etime')) {
                $map .= " and o.create_time <= " . $etime;


            } elseif ($this->_get('stime')) {


                $map .= " and o.create_time >= " . $stime;


            }

        }


        if ($this->is_suppierids > 0) {
            $map .= " and s.supplier_id in(" . $this->suppierids . ")";
        }


        //查询子语句
        $data = $saleDB->alias('s')->where($map)->join('left JOIN __ORDER__ as o on o.id = s.order_id')->group("s.order_id")->Field('o.*')->select();


        $attrvalDB = M('attr_val');
        foreach ($data as $key => $value) {


            $data[$key]['dateline'] = date("Y-m-d", $data[$key]['create_time']);
            $productlist = $saleDB->alias('s')->where(array('s.order_id' => $value['id']))->join('left JOIN __PRODUCT__ as p on p.id = s.product_id')->Field('p.title,s.num,s.price,s.total,s.attr')->select();
            $data[$key]['height'] = count($productlist) * 24;
            $data[$key]['title'] = "";
            $data[$key]['total'] = 0;
            foreach ($productlist as $pkey => $pval) {

                $attrstr = "";
                $attrval = explode(';', $pval['attr']);
                foreach ($attrval as $v) {
                    $mes = $attrvalDB->where(array('id' => $v))->find();
                    $attrstr .= $mes['val'] . '　';
                }
                $data[$key]['title'] .= $pval["title"] . "【" . $attrstr . "  数量：" . $pval['num'] . "  价格：¥" . $pval['price'] . "  小计：¥" . $pval['total'] . "】 \r\n ";

                $data[$key]['total'] += $pval['total'];


            }


        }
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L');
        $tableheader = array('姓名', '地址', '单位名称', '手机电话', '邮编'


        );
        if ($this->_get('getExcel', 'int') == 1) {
            $tableheader[] = "商品列表";
            $tableheader[] = "总价";
            $tableheader[] = "订单号";
            $tableheader[] = "下单时间";
        }
        $excel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
        $excel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
        $excel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
        $excel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        if ($this->_get('getExcel', 'int') == 1) {
            $excel->getActiveSheet()->getColumnDimension('F')->setWidth(50);
            $excel->getActiveSheet()->getColumnDimension('G')->setWidth(32);
            $excel->getActiveSheet()->getColumnDimension('H')->setWidth(16);
            $excel->getActiveSheet()->getColumnDimension('I')->setWidth(40);
            $excel->getActiveSheet()->getColumnDimension('J')->setWidth(40);
        }
        for ($i = 0; $i < count($tableheader); $i++) {

            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");

        }
        for ($i = 2; $i <= count($data) + 1; $i++) {

            $excel->getActiveSheet()->setCellValue('A' . $i, $data[$i - 2]['yourname']);
            $excel->getActiveSheet()->setCellValue('B' . $i, ' ' . $data[$i - 2]['address']);
            $excel->getActiveSheet()->setCellValue('C' . $i, '');
            $excel->getActiveSheet()->setCellValue('D' . $i, ' ' . $data[$i - 2]['tel']);
            $excel->getActiveSheet()->setCellValue('E' . $i, ' ');


            if ($this->_get('getExcel', 'int') == 1) {

                $excel->getActiveSheet()->setCellValue('F' . $i, $data[$i - 2]['title']);
                $excel->getActiveSheet()->setCellValue('G' . $i, ' ' . $data[$i - 2]['total']);
                $excel->getActiveSheet()->setCellValue('H' . $i, ' ' . $data[$i - 2]['ordernumber']);
                $excel->getActiveSheet()->setCellValue('I' . $i, $data[$i - 2]['dateline']);
            }
        }


        $write = new PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="发货明细.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');

        exit;


    }


}
